package test.ps;

import java.io.RandomAccessFile;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.FileChannel.MapMode;
import java.util.Scanner;

import hyl.core.MyDate;

/**
 * 
 * 往 "共享内存" 写入数据
 * 
 */

public class Amem {
	/**
	 * 
	 * @throws Exception
	 * 
	 */

	public static void main(String[] args) throws Exception {
		RandomAccessFile raf = new RandomAccessFile("./swap.mm", "rw");

		FileChannel fc = raf.getChannel();

		MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, 1024);

//清除文件内容

		for (int i = 0; i < 1024; i++) {
			mbb.put(i, (byte) 0);
		}
		// mbb.get(5);//不会引起 指针偏移
		// System.out.println( mbb.position());
		// mbb.position(8);
		// System.out.println( mbb.position());
		Scanner in = new Scanner(System.in);
		while (true) {
			// System.out.println( mbb.position()); 数据长度
			if (mbb.get(0) == (byte)0) {
				String name = in.nextLine();// 读取换行符为间隔的		
				byte bb[] = name.getBytes("utf-8");
				if (bb.length > 1000)
					continue;
				mbb.put(0,(byte)1);
				// 也不会引起指针偏移 是否有新的数据
				mbb.putInt(20, bb.length);
			
				mbb.position(24);
				System.out.println(mbb.position());
				mbb.put(bb);
			}else {
				MyDate.sleep(500);
			}
		}

	}

}
